package com.lyf.juc.practice.lock;

import org.junit.Test;

/**
 * 中断协商机制：
 * 主要理解三个API的意义：
 * 实例的interrupt
 * 静态方法 interrupted
 * isInterrupted()
 *
 * @author LYF
 * @date 2022/7/6
 */
public class InterruptNegotiation {

    /*
    源码阅读分析
     */
    @Test
    public void test0(){
        Thread.currentThread().interrupt();
        Thread.currentThread().isInterrupted();
        Thread.interrupted();
    }

    /*
    简单测试
     */
    @Test
    public void test1() throws InterruptedException {
        Thread thread = new Thread(()->{

            while (true){
                if(Thread.currentThread().isInterrupted()){
                    System.out.println("");
                    break;
                }
                System.out.println("work");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // Sleep中断异常会导致标志位设为false
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }

            }

        });
        thread.start();

        Thread.sleep(10);

        new Thread(()->{
            thread.interrupt();// 协商，设置标志位为true
        }).start();
    }


}
